package com.yan.utils;

import com.alibaba.fastjson.JSON;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpRequest;
import org.springframework.http.client.ClientHttpRequestExecution;
import org.springframework.http.client.ClientHttpRequestInterceptor;
import org.springframework.http.client.ClientHttpResponse;
import org.springframework.http.client.SimpleClientHttpRequestFactory;
import org.springframework.http.client.support.HttpRequestWrapper;
import org.springframework.stereotype.Component;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

import javax.annotation.PostConstruct;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * Vendor rest template
 *
 * @author zhangzhenfeng
 * @since 2016-04-21
 */
@Component
public class VendorRestTemplate {

    private Logger logger = LoggerFactory.getLogger(VendorRestTemplate.class);

    private RestTemplate restTemplate;

    @PostConstruct
    private void init() {
        // set timeout

        SimpleClientHttpRequestFactory requestFactory = new SimpleClientHttpRequestFactory();
        requestFactory.setReadTimeout(20000);
        requestFactory.setConnectTimeout(5000);
        restTemplate = new RestTemplate(requestFactory);
        //
        List<ClientHttpRequestInterceptor> interceptors = new ArrayList<ClientHttpRequestInterceptor>();
        interceptors.add(new HeaderRequestInterceptor());
        restTemplate.setInterceptors(interceptors);
    }

    private static class HeaderRequestInterceptor implements
            ClientHttpRequestInterceptor {
        @Override
        public ClientHttpResponse intercept(HttpRequest request, byte[] body,
                                            ClientHttpRequestExecution execution) throws IOException {
            HttpRequest wrapper = new HttpRequestWrapper(request);
            wrapper.getHeaders().set("Accept-charset", "utf-8");
            return execution.execute(wrapper, body);
        }
    }

    public <T> T get(String url, Class<T> clazz) {
        logger.debug("get: arg url={}", url);
        return restTemplate.getForObject(url, clazz);
    }

    public <T> T postFile(String url, HttpEntity<MultiValueMap> httpEntity,
                          Class<T> clazz) {
        logger.debug("postFile: arg url={},httpEntity={}", url, httpEntity);
        return restTemplate.postForObject(url, httpEntity, clazz);
    }

    public <T> T post(String url, Object body, Class<T> retClazz) {
        logger.debug("post: url={},body={},retClazz={}", url, body, retClazz);

        String jsonBody = JSON.toJSONString(body);

        if (body == null) {
            logger.info("post: JSON body is null.");
            jsonBody = "{}";
        }
        HttpHeaders headers = new HttpHeaders();
        headers.set("Content-type", "application/json;charset=utf-8");
        //
        HttpEntity<String> entity = new HttpEntity<String>(jsonBody, headers);
        return restTemplate.postForObject(url, entity, retClazz);
    }

}
